local a = CreateFrame("Frame")
local Print = function(str) if str then ChatFrame1:AddMessage("|cff33ff99AmmoGnome:|r  "..tostring(str)) end end
local thresh = .40
local bag
local warned = {}

function a.BuyAmmo()
	local item, count = a.GetAmmo()
	local fish, total = a.GetBag()
	local needed = (math.floor((total - count)/200))
	if needed > 0 then
		for MerchID = 0,GetMerchantNumItems() do
			local ItemLinkMerch = GetMerchantItemLink(MerchID)
			if ItemLinkMerch == item then
				for i = 1,needed do
					BuyMerchantItem(MerchID)
				end
				break
			end
		end
	end
end

function a.GetBag()
	for i = 1,4 do
	local BagName = tostring(GetBagName(i))
		if BagName then
		local subtype = select(7, GetItemInfo(BagName))
			if subtype == "Quiver" or subtype == "Ammo Pouch" then
				total = (GetContainerNumSlots(i)*200)
				return i, total
			end
		end
	end
end

function a.GetAmmo()
	local bag = a.GetBag()
	local numslots = GetContainerNumSlots(bag)
	for slot = 1,numslots do
		local ItemLink = GetContainerItemLink(bag, slot)
		if ItemLink then
		local ItemSub = select(6, GetItemInfo(ItemLink))
			if ItemSub == "Projectile" then
				local count = GetItemCount(ItemLink)
				return ItemLink, count
			end
		end
	end
end

function a.Warning()
	local ammo = a.GetAmmo()
	local bag, total = a.GetBag()
	local current = GetItemCount(ammo)
	local per = (math.floor((current/total)*10)/10)
--	Print("bag "..bag.." ammo "..ammo.." total "..total.." current "..current.." per "..per)
	if per < thresh then
		if per == "0.1" or per == "0.2" or per == "0.3" then
			Print("You need more arrows, you currently have "..Current.." left of "..ammo)
		end
	end
end

a:SetScript("OnEvent", function(self, event, ...)
	if event == "MERCHANT_SHOW" then
		a.BuyAmmo()
	elseif event == "BAG_UPDATE" then
		bag = bag or a.GetBag()
		if arg1 == bag then
			a.Warning()
		end
	elseif event == "ADDON_LOADED" then
		if arg1 == "AmmoGnome" then
			local class = select(2, UnitClass("player"))
			if class ~= "HUNTER" then
				DisableAddOn("AmmoGnome")
			end
		end
	end
end)

a:RegisterEvent("MERCHANT_SHOW")
a:RegisterEvent("BAG_UPDATE")
a:RegisterEvent("ADDON_LOADED")